package serialPort

import (
	"sync"
)

type serialBuffer struct {
	mutex  sync.RWMutex
	buffer []byte
	count  int
	size   int
}

func (e *serialBuffer) instance(size int) {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	e.size = size
	e.count = 0
	e.buffer = make([]byte, e.size)
}

func (e *serialBuffer) append(buffer []byte, cnt int) {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	if cnt == 0 || buffer == nil {
		return
	}

	// 场景1：缓冲区还有剩余空间
	if e.count+cnt <= e.size {
		copy(e.buffer[e.count:e.count+cnt], buffer[0:cnt])
		e.count += cnt
		return
	}

	// 场景2：缓冲区已经满了
	if e.count+cnt > e.size {
		// 向前移动cnt字节的数据
		copy(e.buffer[0:e.size-cnt], e.buffer[e.size-cnt:e.size])
		// 复制后面cnt字节的数据
		copy(e.buffer[e.size-cnt:e.size], buffer[0:cnt])
		e.count = e.size
		return
	}

	return
}

func (e *serialBuffer) Count() int {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	return e.count
}

func (e *serialBuffer) Read(buffer []byte) int {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	size := len(buffer)
	if size < e.count {
		cnt := size
		copy(buffer, e.buffer[:cnt])
		e.count -= cnt
		return cnt
	} else {
		cnt := e.count
		e.count = 0
		copy(buffer, e.buffer[:cnt])
		return cnt
	}
}
